package com.atgion.manager.service.impl;

import cn.hutool.core.date.DateUtil;
import com.atgion.manager.properties.MinioProperties;
import com.atgion.manager.service.FileUploadService;
import com.atgion.exception.exception.GlobalException;
import io.minio.*;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.util.Date;
import java.util.UUID;

@Service
@RequiredArgsConstructor
public class FileUploadServiceImpl implements FileUploadService {

    private final MinioProperties minioProperties;

    @Override
    public String upload(MultipartFile file) {
        try {
            // 创建一个Minio的客户端对象
            MinioClient minioClient = MinioClient.builder()
                    .endpoint(minioProperties.getEndpointUrl())     // http://127.0.0.1:9000  minio访问路径
                    .credentials(minioProperties.getAccessKey(), minioProperties.getSecreKey()) // minio密码 minio用户名
                    .build();

            // 判断桶是否存在
            boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioProperties.getBucketName()).build()); // 存储桶名称
            if (!found) {       // 如果不存在，那么此时就创建一个新的桶
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioProperties.getBucketName()).build()); // 存储桶名称
            } else {  // 如果存在打印信息
                System.out.println("Bucket 'spzx-bucket' already exists.");
            }

            // 根据当前日期对上传文件进行分组 20230801
            String dateDir = DateUtil.format(new Date(), "yyyyMMdd");
            String uuid = UUID.randomUUID().toString().replace("-", "");
            //20230801/443e1e772bef482c95be28704bec58a901.jpg
            String fileName = dateDir+"/"+uuid+file.getOriginalFilename();
            System.out.println(fileName);

//            文件上传
            PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                    .bucket(minioProperties.getBucketName()) // 存储桶名称
                    .stream(file.getInputStream(), file.getSize(), -1)
                    .object(fileName)
                    .build();
            minioClient.putObject(putObjectArgs) ;
            return minioProperties.getEndpointUrl() + "/" + minioProperties.getBucketName() + "/" + fileName ;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /*
    * 删除minio文件
    * */
    @Override
    public void deleteFile(String filePath) {
        try {
            // 创建MinioClient对象
            MinioClient minioClient = MinioClient.builder()
                    .endpoint(minioProperties.getEndpointUrl())
                    .credentials(minioProperties.getAccessKey(), minioProperties.getSecreKey())
                    .build();

            // 从文件路径中提取对象名称
            // 示例路径：http://127.0.0.1:9000/image-bucket/20230801/xxx.jpg
            String objectName = filePath.substring(
                    filePath.indexOf(minioProperties.getBucketName()) + minioProperties.getBucketName().length() + 1
            );
            
            System.out.println("Deleting object: " + objectName);
            System.out.println("From bucket: " + minioProperties.getBucketName());

            // 删除文件
            minioClient.removeObject(
                    RemoveObjectArgs.builder()
                            .bucket(minioProperties.getBucketName())
                            .object(objectName)
                            .build()
            );
        } catch (Exception e) {
            e.printStackTrace(); // 打印详细的堆栈信息
            throw new GlobalException("500", "删除文件失败：" + e.getMessage());
        }
    }
}
